package com.hibernate.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.hibernate.model.Location;

@Repository
public class GeoLocationDaoImpl implements GeoLocationDao
{
	@Autowired
	private SessionFactory sessionFactory;

	public GeoLocationDaoImpl()
	{
		
	}

	private Session getCurrentSession()
	{
		Session session = sessionFactory.getCurrentSession();

		return session;
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public List<Location> getNearestLocation(double latitude, double longitude)
	{
		String queryStr = "from Location where (acos(sin(radians(:lat1)) * sin(radians(latitude)) + cos(radians(:lat1)) * cos(radians(latitude)) * cos(radians(:long1) - radians(longitude))) * 6371) between 1 and 5";
		Query query = getCurrentSession().createQuery(queryStr);
		query.setParameter("lat1", latitude);
		query.setParameter("long1", longitude);
		List<Location> locations = query.list();
		return locations;
	}

	@Transactional
	public void insertGeoLocation(Location location)
	{
		Session session = getCurrentSession();
		session.save(location);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public List<Location> getAllLocations() {
		List<Location> list = getCurrentSession().createCriteria(Location.class).list();
		return list;
	}
	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

}
